package utils

import (
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// GetPageFromQuery 获取页码，默认为1
func GetPageFromQuery(c *gin.Context) int {
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil || page < 1 {
		return 1
	}
	return page
}

// GetPageSizeFromQuery 获取每页数量，默认为10，最大为100
func GetPageSizeFromQuery(c *gin.Context) int {
	pageSize, err := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	if err != nil || pageSize < 1 {
		return 10
	}
	if pageSize > 100 {
		return 100
	}
	return pageSize
}

// GetUintFromQuery 获取uint类型的查询参数
func GetUintFromQuery(c *gin.Context, key string) uint {
	val, err := strconv.ParseUint(c.Query(key), 10, 64)
	if err != nil {
		return 0
	}
	return uint(val)
}

// GetUintSliceFromQuery 获取uint切片类型的查询参数，用逗号分隔
func GetUintSliceFromQuery(c *gin.Context, key string) []uint {
	str := c.Query(key)
	if str == "" {
		return nil
	}

	strSlice := strings.Split(str, ",")
	result := make([]uint, 0, len(strSlice))

	for _, s := range strSlice {
		if val, err := strconv.ParseUint(s, 10, 64); err == nil {
			result = append(result, uint(val))
		}
	}

	return result
}

// GetIntFromQuery 获取int类型的查询参数
func GetIntFromQuery(c *gin.Context, key string, defaultVal int) int {
	val, err := strconv.Atoi(c.Query(key))
	if err != nil {
		return defaultVal
	}
	return val
}

// GetBoolFromQuery 获取bool类型的查询参数
func GetBoolFromQuery(c *gin.Context, key string) bool {
	return c.DefaultQuery(key, "false") == "true"
}

// GetStringSliceFromQuery 获取字符串切片类型的查询参数，用逗号分隔
func GetStringSliceFromQuery(c *gin.Context, key string) []string {
	str := c.Query(key)
	if str == "" {
		return nil
	}
	return strings.Split(str, ",")
}
